Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its level order traversal as:

  1. [
  2. [3],
  3. [9,20],
  4. [15,7]
  5. ]

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<List<Integer>> levelOrder(TreeNode root) {
  12. List<List<Integer>> res = new ArrayList<List<Integer>>();
  13. if (root == null) {
  14. return res;
  15. }
  16. // Use a queue to help level order traversal
  17. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  18. queue.offer(root);
  19. queue.offer(null);
  20. List<Integer> list = new ArrayList<Integer>();
  21. while (!queue.isEmpty()) {
  22. TreeNode node = queue.poll();
  23. if (node != null) {
  24. list.add(node.val);
  25. if (node.left != null) {
  26. queue.offer(node.left);
  27. }
  28. if (node.right != null) {
  29. queue.offer(node.right);
  30. }
  31. } else {
  32. res.add(new ArrayList<Integer>(list));
  33. list = new ArrayList<Integer>();
  34. if (!queue.isEmpty()) {
  35. queue.offer(null);
  36. }
  37. }
  38. }
  39. return res;
  40. }
  41. }